#include "Buffer.h"

Buffer::Buffer()
{
  pthread_mutex_init(&mutex_,0);
  sem_init(&full_, 0, 0);
  sem_init(&empty_, 0, BUFFERSIZE);
}

Buffer::~Buffer()
{
  sem_destroy(&full_);
  sem_destroy(&empty_);
}

Buffer::entry Buffer::get()
{
  sem_wait(&full_);
  pthread_mutex_lock(&mutex_);
  
  entry res = buf_.back();
  buf_.pop_back();

  pthread_mutex_unlock(&mutex_);
  sem_post(&empty_);

  return res;
}

void Buffer::put(entry e)
{
  sem_wait(&empty_);
  pthread_mutex_lock(&mutex_);
  
  buf_.push_back(e);

  pthread_mutex_unlock(&mutex_);
  sem_post(&full_);
}

  



